package coco.mogodb.com.module.drug.service.impl;

import coco.mogodb.com.common.dto.TempMap;
import coco.mogodb.com.module.drug.entity.PharmacyDrugs;
import coco.mogodb.com.module.drug.respon.PharmacyDrugsRepository;
import coco.mogodb.com.module.drug.service.DrugsService;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class DrugsServiceImpl implements DrugsService {

    @Resource
    private MongoOperations mongoOperations;

    @Resource
    private PharmacyDrugsRepository pharmacyDrugsRepository;

    @Override
    public ResponseEntity<Object> save(PharmacyDrugs entity) {
        return new ResponseEntity<>(pharmacyDrugsRepository.save(entity), HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Object> findById(String id) {
        return new ResponseEntity<>(pharmacyDrugsRepository.findById(id), HttpStatus.OK);
    }

    /**
     * 分页查询
     * MongoOperations 是MongoTemplate的接口,它的具体实现就是MongoTemplate
     * 所以这里使用MongoTemplate或MongoOperations都可以
     */
    @Override
    public ResponseEntity<Object> findByCondition(TempMap dto) {

        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Integer pageIndex = dto.getInt("pageIndex");
        Integer pageSize = dto.getInt("pageSize");

        PageRequest pageRequest = PageRequest.of(pageIndex - 1, pageSize, sort);

        // 根据实体属性当做查询条件
        PharmacyDrugs pharmacyDrugsCondition = new PharmacyDrugs();
        pharmacyDrugsCondition.setName("糖口服");
        ExampleMatcher matcher = ExampleMatcher.matching()
                // 改变默认字符串匹配方式：**模糊查询**
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                // 改变默认大小写忽略方式：忽略大小写
                .withIgnoreCase(true)
                // 采用“包含匹配”的方式查询
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                // .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.startsWith())  //name字段开头模糊匹配
                // .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.endsWith())  //name字段结尾模糊匹配
                // 忽略属性，不参与查询
                .withIgnorePaths("pageIndex", "pageSize");
        Example<PharmacyDrugs> example = Example.of(pharmacyDrugsCondition, matcher);
        Page<PharmacyDrugs> pharmacyDrugsPage = pharmacyDrugsRepository.findAll(example, pageRequest);

        return new ResponseEntity<>(pharmacyDrugsPage, HttpStatus.OK);
    }
}
